package com.house.java.util;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.log4j.Logger;


public final class DBUtil {
	private static Logger log = Logger.getLogger(DBUtil.class);
	private static DataSource ds;
	// 数据库连接容器，在同一个线程中传递值，一个线程对应一个ThreadLocal对象
	// 比如说 一个请求访问数据库时，就是一个线程，另外一个请求访问数据库就是另一个线程
	// ThreadLocal保证一个请求只用一个连接Connection
	// ThreadLocal可以将Connection对象与当前线程绑定
	private static final ThreadLocal<Connection> connLocal = new ThreadLocal<Connection>();
	static {
		try {
			Properties props = new Properties();
			props.load(DBUtil.class.getClassLoader().getResourceAsStream(
					"db.properties"));
			ds = BasicDataSourceFactory.createDataSource(props);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}

	public static Connection getConnection(){
		Connection conn = connLocal.get();// 先从connLocal中获取连接
		try {
			if (conn == null || conn.isClosed()) {// 如果获取不到，说明当前线程没有获取过连接
					conn = ds.getConnection();
					// 就从连接池中获取一个
					connLocal.set(conn);// 将获取的连接放进connLocal
			}
		} catch (SQLException e) {
			log.error(e.getMessage());
		}
		return conn;
	}

	public static void closeConnection() throws SQLException {
		// 现尝试从connLocal中获取连接
		Connection conn = connLocal.get();
		// 清空connLocal
		connLocal.set(null);
		if (conn != null && !conn.isClosed()) {
			conn.close();
		}
	}
	
	public static void main(String[] args) {
		Connection conn= getConnection();
		System.out.println(conn.hashCode());
		Connection conn1 = getConnection();
		System.out.println(conn1.hashCode());
	}
}
